import React, { useEffect, useRef } from 'react';
import { connect } from 'react-redux'
import { addCount, decrementCount, userLogin } from './../../store/action'
import { useNavigate } from 'react-router-dom';
// 1.映射State到props:
function mapStateToProps(state, ownProps) {
  // console.log(state); //仓库的所有状态：{count: 100, userInfo: {…}, loginState: false, doctors: Array(0)}
  // console.log(ownProps); // {a: '123'}

  return {
    count: state.count,
    userInfo: state.userInfo,
    loginState: state.loginState
  }
}

// 2. 映射方法到props:
function mapDispatchToProps(dispatch, ownProps) {
  return {
    add: (num) => { dispatch(addCount(num)) },
    decrease: (num) => { dispatch(decrementCount(num)) },
    login: (username, password) => {
      dispatch(userLogin({ username, password }))

    }
  }
}

// LoginView是一个纯ui组件：
const LoginView = (props) => {
  const refName = useRef()
  const refPwd = useRef()
  const navigate = useNavigate()  // hooks，相当于hository对象

  console.log(props); //{a: '123'} //connect()(LoginView);后的变化：{a: '123', dispatch: ƒ}
  /* 最后的props: a: '123', count: 100, useInfo: undefined, loginState: false, add: ƒ, decrease,login…}*/
  const { a, count, userInfo, loginState, add, decrease, login } = props

  useEffect(() => {
    if (loginState) {
      navigate("/home")
    }
  }, [loginState])

  return (
    <div>
      <h1>LOGIN</h1>
      <p>a: {a}</p>
      <p>count: {count}</p>
      <div>
        <button type='button' onClick={() => {
          add(100)
        }}>+100+</button>

        <button type='button' onClick={() => {
          decrease(50)
        }}>-50-</button>
      </div>
      <div>
        UserName: <input type="text" ref={refName} />
      </div>
      <div>
        PassWord: <input type="password" ref={refPwd} />
      </div>
      <div>
        <button type="button" onClick={() => {
          login(refName.current.value, refPwd.current.value)
        }}>登录</button>
      </div>
    </div>
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(LoginView);
/* 
connect函数调用后，返回一个容器组件(hoc组件)，调用hoc组件，并传UI组件做参数，返回一个新的组件回来；
 connect( mapStateToProps , mapDispatchToProps ), mapDispatchToProps不传时，默认把dispatch()注入到组件的props中。
*/